"""
get real time data from modbus TCP server
author:zjf
datetime:4-28
"""
from modbus_tk.modbus_tcp import TcpMaster


class ModbusClient(object):
    """
    a class as a modbus client
    """

    def __init__(self, host, port):
        self._host = host
        self._port = port

    def read(self, slave, function, start, quality) -> tuple:
        """
        get data from slave
        :param slave: slave id for:1
        :param function: modbus function
        :param start: modbus slave start address
        :param quality: read data from start address to start address+quality
        :return: tuple
        """
        c = TcpMaster(self._host, self._port)
        try:
            c.open()
            res = c.execute(slave, function, start, quality)
            return res
        except Exception as e:
            return ('error', e)
        finally:
            c.close()


if __name__ == '__main__':
    mc = ModbusClient('127.0.0.1', 502)
    res = mc.read(1, 3, 0, 10)
    print(res)
